<?php
global $_W, $_GPC;
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$teacherTable = 'hellozjx_mapwxapp_teacher';
$subjectTable = 'hellozjx_mapwxapp_subject';
$classTable = 'hellozjx_mapwxapp_classroom';
$teacherRelationTable = "hellozjx_mapwxapp_teachrelation"; //老师关系表

if ($operation == 'display') {
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;
    $keyword = trim($_GPC['keyword']);
    $condition = '';
    if (!empty($keyword)) {
        $condition = " AND name LIKE '%{$keyword}%'";
    }
    $list = pdo_fetchall("SELECT id,sort,name,avatar,teach_age,sex,city,status,money FROM " . tablename($teacherTable) . " WHERE status between 1 and 2 " . $condition . " ORDER BY sort DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
    $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($teacherTable) . " WHERE status between 1 and 2 " . $condition);
    $pager = pagination($total, $pindex, $psize);
} elseif ($operation == 'post') {
    $id = intval($_GPC['id']);
    if (checksubmit('submit')) {
        if(empty($_GPC['subject']) || empty($_GPC['class']) || empty($_GPC['name']) || empty($_GPC['status']) || empty($_GPC['phone']) || empty($_GPC['idcard']))
            message('必填内容不可为空！', $this->createWebUrl('teacher', array('op' => 'display')), 'error');
        if(empty($id)){
            $isExists = pdo_fetch("select id from " . tablename($teacherTable). " where (phone={$_GPC['phone']} or id_card='{$_GPC['idcard']}') and status<>0");
            if($isExists) //查看手机号与身份证号是否有重复
                message('身份证或手机号已存在', $this->createWebUrl('teacher', array('op' => 'display')), 'error');
        }
        $data = array(
            'name' => $_GPC['name'],
            'sex' => $_GPC['sex'],
            'teach_age' => $_GPC['teach_age'],
            'age' => intval($_GPC['age']),
            'phone' => intval($_GPC['phone']),
            'id_card' => $_GPC['idcard'],
            'email' => $_GPC['email'],
            'qualification' => $_GPC['qualification'],
            'avatar' => $_GPC['avatar'],
            'sort' => intval($_GPC['sort']),
            'city' => $_GPC['city'],
            'address'=> $_GPC['address'],
            'longitude' => $_GPC['location']['lng'], //经度
            'latitude' => $_GPC['location']['lat'], //纬度
            'status' => intval($_GPC['status']),
            'detail' => $_GPC['detail'],
            'create_time' => date('Y-m-d H:i:s',time())
        );
        if($td_id>0)
        {
            $data['td_url']=$_GPC['td_url'];
        }
        load()->func('communication');
        $url = 'http://apis.map.qq.com/ws/coord/v1/translate?locations='.$data['latitude'].','.$data['longitude'].'&type=3&key=R2IBZ-3KOWO-OBWWY-SXICZ-4WOGH-WUFKO';
        $content = json_decode($res['content'], true);
        if ($content['status'] === 0) {
            $data['longitude'] = $content['locations'][0]['lng'];
            $data['latitude'] = $content['locations'][0]['lat'];
        }
        pdo_begin(); //开启事务
        if (!empty($id)) {  //添加、修改教师信息表
            unset($data['createtime']);
            $teacherRes = pdo_update($teacherTable, $data, array('id' => $id));
            pdo_delete($teacherRelationTable, array('tid' => $id));//删除原有的课程[防止重复]
        } else {
            $teacherRes = pdo_insert($teacherTable, $data);
            $id = pdo_insertid();
            if(!$id){
                pdo_rollback();
                message('操作失败！', $this->createWebUrl('teacher', array('op' => 'display')), 'error');
            }
        }
        $classInfo = [];
        foreach($_GPC['class'] as $k => $v){    //教师课堂信息
            $classInfo = [
                'type' => 1,
                'type_id' => $v,
                'tid' => $id
            ];
            $relationRes = pdo_insert($teacherRelationTable,$classInfo);
            if(!$relationRes){
                pdo_rollback();
                message('操作失败！', $this->createWebUrl('teacher', array('op' => 'display')), 'error');
            }
        }
        foreach($_GPC['subject'] as $k => $v) {    //教师课程信息
            $classInfo = [
                'type' => 2,
                'type_id' => $v,
                'tid' => $id
            ];
            $relationRes = pdo_insert($teacherRelationTable,$classInfo);
            if(!$relationRes){
                pdo_rollback();
                message('操作失败！', $this->createWebUrl('teacher', array('op' => 'display')), 'error');
            }
        }

        pdo_commit(); //事务提交
        message('更新信息成功！', $this->createWebUrl('teacher', array('op' => 'display')), 'success');
    }
    $teacher = pdo_fetch("select * from " . tablename($teacherTable) . " where id=:id and status <>0 limit 1", array(":id" => $id));
    $subject = pdo_fetchall("select id,name from " . tablename($subjectTable). " where status=1"); //查找所有课程
    $class =  pdo_fetchall("select id,name from " . tablename($classTable)); //查找所有课堂
    $teacherRelation = pdo_fetchall("select type,type_id from ".tablename($teacherRelationTable)." where tid={$id} and status=1"); //查看所有关系
    $cates = array();
    if (!empty($teacherRelation)) {
        foreach ($teacherRelation as $key => $value) {
            $cates[$value['type']][] = $value['type_id'];
        }
    }
}elseif ($operation == 'delete') {
    $id = intval($_GPC['id']);
    $teacher = pdo_fetch("SELECT id FROM " . tablename($teacherTable) . " WHERE id = '{$id}' AND status = 0");
    if (!empty($teacher)) {
        message('抱歉，教师不存在或是已经被删除！', $this->createWebUrl('teacher', array('op' => 'display')), 'error');
    }
    pdo_update($teacherTable,['status'=>0], array('id' => $id));
    message('删除成功', referer(), 'success');
}
include $this->template('teacher');